<?php

namespace backend\services\active;

use backend\extensions\ApiBaseService;
use backend\models\active\ActiveCoupon;
use backend\models\active\ActiveCouponGoods;
use backend\models\config\AdminUser;

/**
 * Desc 优惠券管理服务类
 * @author WMX
 */
class ActiveCouponService extends ApiBaseService
{

    /**
     * 列表
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        //检索条件
        $condition = ['AND'];
        if ($params['name']) {
            $condition[] = ['like', 'name', $params['name'] ?? ''];
        }
        $list = ActiveCoupon::getDataAll($condition, $params['page'], $params['page_size']);
        foreach ($list['list'] as &$value) {
            $value['state_name'] = ActiveCoupon::$state[$value['state']] ?? '';
            $value['type_name'] = ActiveCoupon::$type[$value['type']] ?? '';
            $value['start_time'] = $value['start_time'] ? date('Y-m-d H:i:s', $value['start_time']) : '';
            $value['end_time'] = $value['end_time'] ? date('Y-m-d H:i:s', $value['end_time']) : '';
        }
        return $list;
    }

    /**
     * 新增
     * @param array $params 参数 
     * * */
    public static function create($params)
    {
        $admin = AdminUser::getDataByToken();
        $time = date('Y-m-d H:i:s');
        $params['start_time'] = !empty($params['time']) ? strtotime($params['time'][0]) : '';
        $params['end_time'] = !empty($params['time']) ? strtotime($params['time'][1]) : '';

        $in_rang = $params['range'];
        // $in_brands = !empty($params['brands']) ? $params['brands'] : [];
        $in_cates = !empty($params['cates']) ? $params['cates'] : [];
        $in_goods_arr =  !empty($params['goods']) ? array_unique(explode(',', $params['goods'])) : [];
       

        // $ex_brands = !empty($params['ex_brands']) ? $params['ex_brands'] : [];
        $ex_cates = !empty($params['ex_cates']) ? $params['ex_cates'] : [];
        $ex_goods_arr = !empty($params['ex_goods']) ? array_unique(explode(',', $params['ex_goods'])) : [];

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $cp_data = [
                'name' => $params['name'],
                'type' => $params['type'],
                'time_type' => $params['time_type'],
                'count' => $params['count'],
                'usable_count' => $params['count'],
                'start_time' => $params['start_time'],
                'end_time' => $params['end_time'],
                'denomination' => $params['denomination'],
                'threshold' => $params['threshold'],
                'state' => $params['state'],
                'operator_id' => $admin['id'],
                'desc' => $params['desc'],
                'data' => $params['data'],
                'sort' => $params['sort'],
                'create_time' => $time,
                'update_time' => $time,
                'effect_day' => $params['effect_day'] ?? 0,
            ];
            $cp_id = ActiveCoupon::create($cp_data);

            $cp_goods = [];

            if (in_array(ActiveCouponGoods::RANGE_ALL, $in_rang)) {
                $cp_goods[] = [
                    'type' => 1,
                    'active_coupon' => $cp_id,
                    'range' => 4,
                    'create_time' => $time,
                    'gid' => 0,
                    'start_time' => $params['start_time'],
                    'end_time' => $params['end_time'],
                    'state' => $params['state'],
                    'time_type' => $params['time_type'],
                ];
            } else {
                // foreach ($in_brands as $val) {
                //     $cp_goods[] = [
                //         'type' => 1,
                //         'active_coupon' => $cp_id,
                //         'range' => 2,
                //         'create_time' => $time,
                //         'gid' => $val,
                //         'start_time' => $params['start_time'],
                //         'end_time' => $params['end_time'],
                //         'state' => $params['state'],
                //         'time_type' => $params['time_type']
                //     ];
                // }
                foreach ($in_cates as $val) {
                    $cp_goods[] = [
                        'type' => 1,
                        'active_coupon' => $cp_id,
                        'range' => 3,
                        'create_time' => $time,
                        'gid' => $val,
                        'start_time' => $params['start_time'],
                        'end_time' => $params['end_time'],
                        'state' => $params['state'],
                        'time_type' => $params['time_type']
                    ];
                }
                foreach ($in_goods_arr as $val) {
                    $cp_goods[] = [
                        'type' => 1,
                        'active_coupon' => $cp_id,
                        'range' => 1,
                        'create_time' => $time,
                        'gid' => $val,
                        'start_time' => $params['start_time'],
                        'end_time' => $params['end_time'],
                        'state' => $params['state'],
                        'time_type' => $params['time_type']
                    ];
                }
            }


            // foreach ($ex_brands as $val) {
            //     $cp_goods[] = [
            //         'type' => 2,
            //         'active_coupon' => $cp_id,
            //         'range' => 2,
            //         'create_time' => $time,
            //         'gid' => $val,
            //         'start_time' => $params['start_time'],
            //         'end_time' => $params['end_time'],
            //         'state' => $params['state'],
            //         'time_type' => $params['time_type']
            //     ];
            // }
            foreach ($ex_cates as $val) {
                $cp_goods[] = [
                    'type' => 2,
                    'active_coupon' => $cp_id,
                    'range' => 3,
                    'create_time' => $time,
                    'gid' => $val,
                    'start_time' => $params['start_time'],
                    'end_time' => $params['end_time'],
                    'state' => $params['state'],
                    'time_type' => $params['time_type']
                ];
            }
            foreach ($ex_goods_arr as $val) {
                $cp_goods[] = [
                    'type' => 2,
                    'active_coupon' => $cp_id,
                    'range' => 1,
                    'create_time' => $time,
                    'gid' => $val,
                    'start_time' => $params['start_time'],
                    'end_time' => $params['end_time'],
                    'state' => $params['state'],
                    'time_type' => $params['time_type']
                ];
            }

            \Yii::$app->db->createCommand()->batchInsert(ActiveCouponGoods::tableName(), array_keys($cp_goods[0]), $cp_goods)->execute();


            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }

    /**
     * 新增
     * @param array $params 参数 
     * * */
    public static function update($params)
    {
        $id = $params['id'];
        $admin = AdminUser::getDataByToken();
        $time = date('Y-m-d H:i:s');
        $params['start_time'] = !empty($params['time']) ? strtotime($params['time'][0]) : '';
        $params['end_time'] = !empty($params['time']) ? strtotime($params['time'][1]) : '';

        $in_rang = $params['range'];
        // $in_brands = !empty($params['brands']) ? $params['brands'] : [];
        $in_cates = !empty($params['cates']) ? $params['cates'] : [];
        $in_goods_arr =  !empty($params['goods']) ? array_unique(explode(',', $params['goods'])) : [];

        // $ex_brands = !empty($params['ex_brands']) ? $params['ex_brands'] : [];
        $ex_cates = !empty($params['ex_cates']) ? $params['ex_cates'] : [];
        $ex_goods_arr = !empty($params['ex_goods']) ? array_unique(explode(',', $params['ex_goods'])) : [];

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            ActiveCouponGoods::deleteAll(['active_coupon' => $id]);

            $cp_data = [
                'name' => $params['name'],
                'type' => $params['type'],
                'time_type' => $params['time_type'],
                'count' => $params['count'],
                'start_time' => $params['start_time'],
                'end_time' => $params['end_time'],
                'denomination' => $params['denomination'],
                'threshold' => $params['threshold'],
                'state' => $params['state'],
                'operator_id' => $admin['id'],
                'desc' => $params['desc'],
                'data' => $params['data'],
                'sort' => $params['sort'],
                'update_time' => $time,
                'effect_day' => $params['effect_day'] ?? 0,
            ];
            ActiveCoupon::updateData($cp_data, ['id' => $id]);
            $cp_id = $id;
            $cp_goods = [];

            if (in_array(ActiveCouponGoods::RANGE_ALL, $in_rang)) {
                $cp_goods[] = [
                    'type' => 1,
                    'active_coupon' => $cp_id,
                    'range' => 4,
                    'create_time' => $time,
                    'gid' => 0,
                    'start_time' => $params['start_time'],
                    'end_time' => $params['end_time'],
                    'state' => $params['state'],
                    'time_type' => $params['time_type']
                ];
            } else {
                // foreach ($in_brands as $val) {
                //     $cp_goods[] = [
                //         'type' => 1,
                //         'active_coupon' => $cp_id,
                //         'range' => 2,
                //         'create_time' => $time,
                //         'gid' => $val,
                //         'start_time' => $params['start_time'],
                //         'end_time' => $params['end_time'],
                //         'state' => $params['state'],
                //         'time_type' => $params['time_type']
                //     ];
                // }
                foreach ($in_cates as $val) {
                    $cp_goods[] = [
                        'type' => 1,
                        'active_coupon' => $cp_id,
                        'range' => 3,
                        'create_time' => $time,
                        'gid' => $val,
                        'start_time' => $params['start_time'],
                        'end_time' => $params['end_time'],
                        'state' => $params['state'],
                        'time_type' => $params['time_type']
                    ];
                }
                foreach ($in_goods_arr as $val) {
                    $cp_goods[] = [
                        'type' => 1,
                        'active_coupon' => $cp_id,
                        'range' => 1,
                        'create_time' => $time,
                        'gid' => $val,
                        'start_time' => $params['start_time'],
                        'end_time' => $params['end_time'],
                        'state' => $params['state'],
                        'time_type' => $params['time_type']
                    ];
                }
            }


            // foreach ($ex_brands as $val) {
            //     $cp_goods[] = [
            //         'type' => 2,
            //         'active_coupon' => $cp_id,
            //         'range' => 2,
            //         'create_time' => $time,
            //         'gid' => $val,
            //         'start_time' => $params['start_time'],
            //         'end_time' => $params['end_time'],
            //         'state' => $params['state'],
            //         'time_type' => $params['time_type']
            //     ];
            // }
            foreach ($ex_cates as $val) {
                $cp_goods[] = [
                    'type' => 2,
                    'active_coupon' => $cp_id,
                    'range' => 3,
                    'create_time' => $time,
                    'gid' => $val,
                    'start_time' => $params['start_time'],
                    'end_time' => $params['end_time'],
                    'state' => $params['state'],
                    'time_type' => $params['time_type']
                ];
            }
            foreach ($ex_goods_arr as $val) {
                $cp_goods[] = [
                    'type' => 2,
                    'active_coupon' => $cp_id,
                    'range' => 1,
                    'create_time' => $time,
                    'gid' => $val,
                    'start_time' => $params['start_time'],
                    'end_time' => $params['end_time'],
                    'state' => $params['state'],
                    'time_type' => $params['time_type']
                ];
            }

            \Yii::$app->db->createCommand()->batchInsert(ActiveCouponGoods::tableName(), array_keys($cp_goods[0]), $cp_goods)->execute();


            $transaction->commit();
            return self::jsonSuccess();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return self::jsonError($e->getMessage());
        }
    }


    /**
     * 详情
     * @param array $params 参数 
     * **/
    public static function detail($params)
    {
        $condition = ['id' => $params['id']];
        $data = ActiveCoupon::getDataOne($condition, '', []);
        $data['time'] = [date('Y-m-d H:i:s', $data['start_time']), date('Y-m-d H:i:s', $data['end_time'])];

        $link_condition = ActiveCouponGoods::getAll(['active_coupon' => $params['id']]);

        $data['range'] = [];
        // $data['brands'] = [];
        $data['cates'] = [];
        $data['goods'] = [];

        $data['ex_range'] = [];
        // $data['ex_brands'] = [];
        $data['ex_cates'] = [];
        $data['ex_goods'] = [];
        foreach ($link_condition as $val) {
            if ($val['type'] == 1) {
                $data['range'][] = $val['range'];
                if ($val['range'] == 1) {
                    $data['goods'][] = $val['gid'];
                } elseif ($val['range'] == 2) {
                    // $data['brands'][] = $val['gid'];
                } elseif ($val['range'] == 3) {
                    $data['cates'][] = $val['gid'];
                }
            } elseif ($val['type'] == 2) {
                $data['ex_range'][] = $val['range'];
                if ($val['range'] == 1) {
                    $data['ex_goods'][] = $val['gid'];
                } elseif ($val['range'] == 2) {
                    // $data['ex_brands'][] = $val['gid'];
                } elseif ($val['range'] == 3) {
                    $data['ex_cates'][] = $val['gid'];
                }
            }
        }

        $data['range'] = array_values(array_unique($data['range']));
        $data['ex_range'] = array_values(array_unique($data['ex_range']));
        $data['goods'] = implode(',', $data['goods']);
        $data['ex_goods'] = implode(',', $data['ex_goods']);
        return self::jsonSuccess($data);
    }
}
